/*
 * @Author: huangjinyao huangjinyao@hjy.cn
 * @Date: 2024-07-02 09:21:10
 * @LastEditors: 朝言夕识 11442050+we-know-each-other-every-day@user.noreply.gitee.com
 * @LastEditTime: 2024-07-06 10:23:55
 * @FilePath: \小兔仙项目\vue-rabbit\src\utils\http.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
//封装axios
import axios from 'axios'
import { ElMessage } from "element-plus";
import { useUserStore } from '@/stores/userStore'
import "element-plus/theme-chalk/el-message.css";
import router from '@/router'


const httpInstance = axios.create({
    baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net/',
    timeout: 50000

})

//axios请求拦截器
httpInstance.interceptors.request.use(config => {
    const userStore = useUserStore()

    const token = userStore.userInfo.token
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }


    return config
}, e => Promise.reject(e))

//axios响应拦截器
httpInstance.interceptors.response.use(res => res.data, e => {
    if (e.response) {
        //有响应
        ElMessage({
            type: 'error',
            message: e.response.data.message
        })
    }
    console.log(e.response);
    const userStore = useUserStore()
    if (e.response.status === 401) {
        //token失效
        userStore.clearUserInfo()
        //跳转到登录页
        router.push('/login')
    }


    return Promise.reject(e)
})



export default httpInstance